package cn.plugins.generator.task

import cn.plugins.generator.utils.GenerateMarkdownUtil
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.TaskAction

/**
 * 创建于 2020-01-08 16:37
 *
 * @author jiangyun
 * @类说明 任务类
 */
open class GenerateMarkdownTask : DefaultTask() {

    lateinit var dbType: String                 // 数据库类型
    lateinit var url: String                    // 数据库连接地址
    lateinit var port: String                   // 端口
    lateinit var database: String               // 数据库名称
    lateinit var userName: String               // 用户名
    lateinit var password: String               // 密码
    lateinit var projectPath: String            // 文件生成目录

    @TaskAction
    fun generateAction() {
        if (dbType.isBlank()) {
            println("database type can't be null or empty")
            return
        }
        /*if (dbType != "mysql" || dbType != "postgresql") {
            printlnln("database type only surport mysql or postgresql")
            return
        }*/
        if (url.isBlank()) {
            println("url can't be null or empty")
            return
        }
        if (port.isBlank()) {
            println("port can't be null or empty")
            return
        }
        if (database.isBlank()) {
            println("databaseName can't be null or empty")
            return
        }
        if (userName.isBlank()) {
            println("userName can't be null or empty")
            return
        }
        if (password.isBlank()) {
            println("password can't be null or empty")
            return
        }
        if (projectPath.isBlank()) {
            println("genrate file path can't be null or empty")
            return
        }

        url = when(dbType) {
            "mysql" -> "jdbc:mysql://${url}:${port}/${database}?useUnicode=true&serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=UTF-8&allowPublicKeyRetrieval=true&autoReconnect=true&failOverReadOnly=false&tinyInt1isBit=false"
            "postgresql" -> "jdbc:postgresql://${url}:${port}/${database}"
            // "h2" -> "jdbc:h2:"
            else -> ""
        }

        try {
            println("========================== start export database ==========================")
            println("========================== author: iwiteks-jy    ==========================")
            println("========================== version: 1.0.6        ==========================")

            GenerateMarkdownUtil.export(dbType, url, database, userName, password, projectPath)
        } catch (ex: Exception) {
            println(ex)
        } finally {
            println("========================== end generate code ==========================")
        }
    }
}